package com.lgkj.ui.userinfo;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RadioButton;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.lgkj.R;
import com.lgkj.adapter.OrderAdapter;
import com.lgkj.bean.meitao.OrderListBean;
import com.lgkj.ui.BaseActivity;
import com.lgkj.ui.shop.ComfirHarvestOrderActivity;
import com.lgkj.ui.shop.ShopCommentActivity;
import com.lgkj.utils.CommonConstant;
import com.lgkj.utils.HttpUtils;
import com.lgkj.utils.PayResult;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/8/20 0020.
 */

public class OrderActivity extends BaseActivity {
    @BindView(R.id.lv_item)
    ListView lvItem;
    @BindView(R.id.rb_tab2)
    RadioButton rbTab2;
    @BindView(R.id.srl_refresh)
    SmartRefreshLayout srlRefresh;
    private OrderAdapter adapter;
    private OrderListBean orderListBean;
    private int page = 0;
    private String status = "0";
    private boolean nopay = false;

    @Override
    public int getLayoutId() {
        return R.layout.activity_order;
    }

    @Override
    public void initView() {
        setTitle("我的订单");
        adapter = new OrderAdapter(OrderActivity.this);
        lvItem.setAdapter(adapter);
//        srlRefresh.setOnLoadmoreListener(new OnLoadmoreListener() {
//            @Override
//            public void onLoadmore(RefreshLayout refreshlayout) {
//                page++;
//                getOrderList(status, nopay);
//            }
//        });
//        srlRefresh.setOnRefreshListener(new OnRefreshListener() {
//            @Override
//            public void onRefresh(RefreshLayout refreshlayout) {
//                page = 1;
//                getOrderList(status, nopay);
//            }
//        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        status = "0";
        nopay = false;
        getOrderList(status, nopay);
        rbTab2.setChecked(true);
    }

    @Override
    public void initData() {
        adapter.setCallBack(new OrderAdapter.CallBack() {
            @Override
            public void gopay(int i) {
                ItemBtnClick(i);
//                Intent intent = new Intent(OrderActivity.this, ShopCommentActivity.class);
//                intent.putExtra("order_id", "1");
//                startActivity(intent);

            }
        });

        lvItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                OrderListBean.DataBeanX.DataBean dataBean = adapter.getItem(i);
                if (dataBean.getPay_status().equals("0"))
                    showDetela(adapter.getItem(i).getOrder_no());
//                Intent intent = new Intent(OrderActivity.this, OrderDetailsActivity.class);
//                intent.putExtra("order_id", adapter.getItem(i).getId());
//                startActivity(intent);
            }
        });
    }

    private void showDetela(final String order_no) {
        AlertDialog.Builder builder = new AlertDialog.Builder(OrderActivity.this);
        //    设置Title的图标
        //    设置Title的内容
        builder.setTitle("订单");
        //    设置Content来显示一个信息
        builder.setMessage("确定删除订单吗？");
        //    设置一个PositiveButton
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteOrder(order_no);
            }
        });
        //    设置一个NegativeButton
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        //    显示出该对话框
        builder.show();
    }

    @OnClick({R.id.rb_tab2, R.id.rb_tab3, R.id.rb_tab4, R.id.rb_tab5, R.id.rb_tab6})
    public void onClick(View view) {
        nopay = true;
        //order_status（发货状态 0未发货 1已发货 2已收货 3已评价） *
        // 0 未支付 1已支付
        switch (view.getId()) {
            case R.id.rb_tab2:
                status = "0";
                nopay = false;
                break;
            case R.id.rb_tab3:
                status = "0";
                break;
            case R.id.rb_tab4:
                status = "1";
                break;
            case R.id.rb_tab6:
                status = "3";
                break;
            case R.id.rb_tab5:
                status = "2";
                break;

        }
        getOrderList(status, nopay);
    }

    private void getOrderList(String status, boolean noPay) {
        showDiaLog("正在获取数据");
        Map<String, String> map = new HashMap<>();
        map.put("access_token", getToken());
        map.put("order_status", status);
        if (noPay)
            map.put("pay_status", "1");
        else
            map.put("pay_status", "0");

        map.put("page", page + "");
        HttpUtils.postHttp(map, CommonConstant.getOrderListByStatus, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                dismissDiaLog();
                if (jsonObject.optInt("code") == 0) {
                    Gson mGson = new Gson();
                    orderListBean = mGson.fromJson(String.valueOf(jsonObject), OrderListBean.class);
                    if (orderListBean.getData().getData() != null) {
                        adapter.setData(orderListBean.getData().getData());
                        adapter.notifyDataSetChanged();
                    }
                } else {
                    toastLong(jsonObject.optString("msg"), 0);
                }
            }

            @Override
            public void errorHttp(String msg) {
                dismissDiaLog();
            }
        });
    }

    /**
     * /0未发货 1已发货 2已收货 3已评价）
     *
     * @param position
     */
    private void ItemBtnClick(int position) {
        OrderListBean.DataBeanX.DataBean beans = orderListBean.getData().getData().get(position);
        int status = 0;
        try {
            status = Integer.parseInt(beans.getOrder_status());
        } catch (Exception e) {
        }
        switch (status) {
            case 0:
                if (beans.getPay_status().equals("0")) {
                    goPay(beans.getOrder_no());
                } else {
                    toastLong("催单成功，等待商家发货", 0);
                }
                break;
            case 1:
                Intent intent1 = new Intent(OrderActivity.this, ComfirHarvestOrderActivity.class);
                intent1.putExtra("orderNo", adapter.getItem(position).getId());
                startActivity(intent1);
                break;
            case 2:
                Intent intent3 = new Intent(OrderActivity.this, ShopCommentActivity.class);
                intent3.putExtra("image_url", adapter.getItem(position).getCover_id());
                intent3.putExtra("goods_id", adapter.getItem(position).getGoods_id());
                intent3.putExtra("goods_model_id", adapter.getItem(position).getGoods_model_id());
                startActivity(intent3);
                break;
            case 3:
                break;
        }
    }

    private void goPay(String orderNo) {
        showDiaLog("正在获取数据");
        Map<String, String> map = new HashMap<>();
        map.put("access_token", getToken());
        map.put("order_no", orderNo);
        HttpUtils.postHttp(map, CommonConstant.rePay, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                dismissDiaLog();
                if (jsonObject.optInt("code") == 0) {
                    String result = jsonObject.optJSONObject("data").optString("result");
                    if (jsonObject.optJSONObject("data").optString("pay_type").equals("1")) {   //微信

                    } else {
//                         result = "alipay_sdk=alipay-sdk-php-20180705&app_id=2016092201947846&biz_content=%7B%22body%22%3A%22%22%2C%22subject%22%3A%22%5Cu7f8e%5Cu70b9%5Cu4f18%5Cu6dd8-%5Cu8ba2%5Cu5355%5Cu7f16%5Cu53f7%3A20181121140822827851396%22%2C%22out_trade_no%22%3A%2220181121140822827851396%22%2C%22timeout_express%22%3A%221d%22%2C%22total_amount%22%3A0%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%7D&charset=UTF-8&format=json&method=alipay.trade.app.pay&notify_url=http%3A%2F%2Fmdyt.lianguangtech.com%2Fnotify&sign_type=RSA2&timestamp=2018-11-21+14%3A15%3A34&version=1.0&sign=a7NLdnGtC3xB2Yrk9vXalvI%2BsQdB4fbCT6Vt6xfY7pwm%2Bc2ShYfUpsHTXPPIoq5BJN8dFzK7wt5u%2BUTLntonGkJjq2UNnkq54wKcSJMJ9pQZhCrxsRFZyqR5H0fbC7%2F%2BRNDZZfF%2BKj7HG4kOyIYYN1HnGpDduAIn%2BAksXWALEbdXC43HX50do22XCKxN3%2BWdKyJA3FVFyqFPtBr%2B0NmXVt8DnCP4X2jy1QY6pB2mqqysLZtWIldH5qirn66G67oU2c8Tf8EbAfgN4izdZB3PvXeLvvv%2BvfXeVN3TXygwme7umJEdjsUio91yLbHQUXz6Ip0WkLSp%2FRVuYhQIa2mJNg%3D%3D";
                        zfbPay(result);
                    }
                } else {
                    toastLong(jsonObject.optString("msg"), 0);
                }
            }

            @Override
            public void errorHttp(String msg) {
                dismissDiaLog();
            }
        });
    }


    private void zfbPay(final String orderInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(OrderActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());
                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultStatus = payResult.getResultStatus();
                    Log.i(TAG, "handleMessage: " + resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        toastLong("支付成功", 0);
                    } else {
                        toastLong("支付失败", 0);
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    }
                    break;
            }
        }
    };

    private void deleteOrder(String orderId) {
        Map<String, String> map = new HashMap<>();
        map.put("access_token", getToken());
        map.put("order_no", orderId);
        HttpUtils.postHttp(map, CommonConstant.delOrder, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                toastLong(jsonObject.optString("msg"), 0);
                if (jsonObject.optInt("code") == 0) {
                    getOrderList(status, nopay);
                }
            }

            @Override
            public void errorHttp(String msg) {

            }
        });
    }
}
